package com.noodles.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.noodles.mall.entity.*;
import com.noodles.mall.mapper.UserMapper;
import com.noodles.mall.service.UserRoleService;
import com.noodles.mall.service.UserService;
import com.noodles.mall.vo.PageVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/** 用户 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserRoleService userRoleService;

    /** 增加 **/
    public User insert(User user){
        if(super.save(user)) return selectOne(user.getUsername());
        return null;
    }

    /** 删除: 单个或批量 **/
    public boolean delete(List<Integer> ids){
        try {
            ids.forEach(id->{
                super.update(new UpdateWrapper<User>().lambda()
                        .set(User::getIsEnabled,false)
                        .eq(User::getId,id)
                );
            });
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /** 修改: 根据id修改所有 **/
    public boolean update(User user){
        return super.updateById(user);
    }

    /** 修改: image_url **/
    public boolean updateUrl(Integer id, String url){
        return super.update(new UpdateWrapper<User>().lambda()
                .set(User::getAvatarUrl,url)
                .eq(User::getId,id)
        );
    }

    /** 单个查询: id **/
    public User selectOne(Integer id){
        User user=super.getById(id);
        user.setRoleList(userRoleService.selectList(user.getId()));
        return user;
    }

    /** 单个查询: username **/
    public User selectOne(String username){
        User user=super.getOne(new QueryWrapper<User>().lambda()
                .eq(User::getUsername,username)
        );
        if(user!=null) user.setRoleList(userRoleService.selectList(user.getId()));
        return user;
    }

    /** 查询用户数量 **/
    public Integer selectCount(){
        return super.count();
    }

    /** 查询列表: 性别比例 **/
    public List<Map<String, Object>> selectListWithSexRatio(){
        List<Map<String,Object>> list=super.listMaps(new QueryWrapper<User>()
                .select("sex as col,count(*) as total").lambda()
                .isNotNull(User::getSex)
                .groupBy(User::getSex));
        list.forEach(map->{
            if((boolean) map.get("col")) map.put("col","女");
            else map.put("col","男");
        });
        return list;
    }

    /** 分页查询: wrapper **/
    public PageVo selectPage(Long current, Long size, LambdaQueryWrapper<User> wrapper){
        Page<User> page = super.page(new Page<>(current, size), wrapper
                .orderByDesc(User::getCreatedTime)
        );
        page.getRecords().forEach(user ->{
            if(user!=null) user.setRoleList(userRoleService.selectList(user.getId()));
        }); // 注入角色信息
        return PageVo.getPageVo(page);
    }

    /** 分页查询: 无 **/
    public PageVo selectPage(Long current, Long size){
        return selectPage(current,size,new QueryWrapper<User>().lambda());
    }

    /** 分页查询: word **/
    public PageVo selectPage(Long current, Long size, String word){
        return selectPage(current,size,new QueryWrapper<User>().lambda()
                .like(User::getId,word).or()
                .like(User::getNickname,word).or()
                .like(User::getUsername,word)
        );
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = selectOne(username);
        if (user == null) throw new UsernameNotFoundException("用户名" + username + "不存在");
        user.setRoleList(userRoleService.selectList(user.getId()));
        UserExt userExt = new UserExt();
        BeanUtils.copyProperties(user, userExt);
        return userExt;
    }
}
